package aliyun.cx.admin.service.impl;

import aliyun.cx.admin.entity.Album;
import aliyun.cx.admin.mapper.AlbumMapper;
import aliyun.cx.admin.service.AlbumService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 相册Service实现类
 */
@Service
public class AlbumServiceImpl extends ServiceImpl<AlbumMapper, Album> implements AlbumService {
    
    @Override
    public Page<Album> getAlbumPage(Integer current, Integer size, String name) {
        Page<Album> page = new Page<>(current, size);
        QueryWrapper<Album> queryWrapper = new QueryWrapper<>();
        
        // 如果提供了名称，进行模糊查询
        if (StringUtils.hasText(name)) {
            queryWrapper.like("name", name);
        }
        
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        
        return this.page(page, queryWrapper);
    }
    
    @Override
    public boolean checkAlbumExists(String name, Long excludeId) {
        QueryWrapper<Album> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        
        // 如果提供了排除ID，则排除该记录
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        
        return this.count(queryWrapper) > 0;
    }
    
    @Override
    public boolean save(Album album) {
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        album.setCreateTime(now);
        album.setUpdateTime(now);
        
        return super.save(album);
    }
    
    @Override
    public boolean updateById(Album album) {
        // 设置更新时间
        album.setUpdateTime(LocalDateTime.now());
        
        return super.updateById(album);
    }
}
